//
//  HistoryVM.m
//  MyDemo
//
//  Created by jay on 2020/8/23.
//  Copyright © 2020 jay. All rights reserved.
//

#import "HistoryVM.h"
#import "JRDB.h"

@implementation HistoryVM

-(id)init {
    self = [super init];
    if (self) {
        self.pagenum = 0;
        self.pagesize = 20;
    }
    return self;
}

- (void)getDataFromNet:(BOOL )isReqMore completeHandle:(void(^)(NSError *error))completionHandle {
    
    TX_WS(weakSelf);
    
    //在后台线程加载数据
    TX_THREAD_BACK(^{
       
        if (!isReqMore) {
            weakSelf.pagenum = 0;
        } else {
            weakSelf.pagenum++;
        }
        
        //总数据个数
        NSUInteger total = J_SelectCount(HistoryModel).count;
        
        //获取分页数据
        NSArray<HistoryModel *> *list = J_Select(HistoryModel)
        .Recursive(NO)
        .Sync(YES)
        .Desc(YES)
        .Order(@"timestamp")
        .Limit(self.pagenum*self.pagesize, self.pagesize)
        .list;
        
        if (!isReqMore) {
            [weakSelf.dataArr removeAllObjects];
        }
        if (list.count > 0) {
            [weakSelf.dataArr addObjectsFromArray:list];
        }
        
        weakSelf.hasNext = (total > [weakSelf.dataArr count]);
            
        //切回主线程，以便刷新UI操作
        TX_THREAD_MAIN(^{

            completionHandle(nil);
        });
    });
}

- (NSInteger)rowNumber {
    return self.dataArr.count;
}

- (HistoryModel *)modelForRow:(NSInteger )row {
    return self.dataArr[row];
}

- (NSString *)titleForRow:(NSInteger )row {
    HistoryModel *model_ = [self modelForRow:row];
    NSString *time = [[TXDateTimeService sharedInstance] stringFromTimeInterval:model_.timestamp format:@"YYYY-MM-dd HH:mm:ss"];
    return time;
}

- (GithubModel *)gitModelForRow:(NSInteger )row {
    HistoryModel *model_ = [self modelForRow:row];
    
    NSDictionary *gitJson_ = [model_.data mj_JSONObject];
    GithubModel *gitModel_ = [GithubModel mj_objectWithKeyValues:gitJson_];
    
    return gitModel_;
}

#pragma mark - Getter

- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray new];
    }
    return _dataArr;
}

@end
